package com.yupi.springbootinit.job.cycle;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.controller.ChartController;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.CosManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

//@Component
@Slf4j
public class GenChartRetry {


    @Resource
    private ChartService chartService;

    @Resource
    private CosManager cosManager;

    @Scheduled(cron = "0 * * * * *")
    public void run(){
        LambdaQueryWrapper<Chart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Chart::getStatus,"failed");
        List<Chart> list = chartService.list(lambdaQueryWrapper);
        if(list==null||list.size()==0){
            return;
        }

        log.info("查询到失败图表，开始重试请求：{}",list);
        for (Chart chart : list) {
            //创建请求的key
            String filepath = String.format("/%s/%s/%s.%s","genChartByAi",chart.getUserId(),"chart_"+chart.getId(),"xlsx");
            try {
                cosManager.pullObject(filepath);
                File file = new File(filepath);
                chartService.sycnGenChartByAi(chart,file);
                try {
                    Thread.sleep(60000);//主线程等待一分钟，别让JVM结束了
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //操作成功后，删除云服务器上文件
                if(chartService.getById(chart.getId()).getStatus().equals("succeed")){
                    cosManager.deleteObject(filepath);
                }
            } catch (IOException e) {
                log.info("{}重试失败",chart);
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"下拉文件失败,{}");
            }
        }
    }
}
